import json
import requests
import frappe
from datetime import datetime

def get_token():
    wxwork_token = frappe.cache().get("wxwork_token")
    if not wxwork_token:
        wxwork_setting = frappe.get_doc('wxwork_setting')
        # print('1111111111111')
        # print(wxwork_setting.corpid)
        # print(wxwork_setting.get_password('app_secret'))        
        kw = {'corpid':wxwork_setting.corpid,'corpsecret':wxwork_setting.get_password('app_secret')} 
        response = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?", params = kw)
        token_result = response.json()
        print(token_result)
        if token_result['errcode'] == 0 :
            wxwork_token = token_result['access_token']
            expire_seconds = token_result['expires_in']            
            frappe.cache().set(name="wxwork_token", value=wxwork_token, ex=expire_seconds-1200)
    return wxwork_token 
    

def refresh_token():
    wxwork_setting = frappe.get_doc('wxwork_setting')
    # print('1111111111111')
    # print(wxwork_setting.corpid)
    # print(wxwork_setting.get_password('app_secret'))
    wxwork_token = frappe.get_doc('wxwork_token')
    kw = {'corpid':wxwork_setting.corpid,'corpsecret':wxwork_setting.get_password('app_secret')} 
    response = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?", params = kw)
    token_result = response.json()
    print(token_result)
    if token_result['errcode'] == 0 :         
        wxwork_token.app_token = token_result['access_token']
        wxwork_token.app_expire = token_result['expires_in']
        wxwork_token.app_refresh_time = datetime.now()        
    kw2 = {'corpid':wxwork_setting.corpid,'corpsecret':wxwork_setting.get_password('address_secret')} 
    response2 = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?", params = kw2)
    token_result2 = response2.json()
    print(token_result2)
    if token_result['errcode'] == 0 :        
        wxwork_token.address_token = token_result2['access_token']
        wxwork_token.address_expire = token_result2['expires_in']
        wxwork_token.address_refresh_time = datetime.now()
    wxwork_token.save(ignore_permissions=True,ignore_version=True)

def sync_users():
    wxwork_token = frappe.get_doc('wxwork_token')
    response = requests.post("https://qyapi.weixin.qq.com/cgi-bin/user/list_id?access_token="+wxwork_token.address_token)
    user_list = response.json()
    print(user_list)
    if user_list['errcode'] == 0:
        dept_users = user_list['dept_user']
        for dept_user in dept_users:
            print(dept_user)
            kw3 = {'access_token':wxwork_token.app_token,'userid':dept_user['userid']}
            response3 = requests.get("https://qyapi.weixin.qq.com/cgi-bin/user/get?", params = kw3)
            user_info = response3.json()
            print(user_info)
            if not frappe.db.exists('wxwork_user_mapping', dept_user['userid']):
                doc = frappe.new_doc('wxwork_user_mapping')
                doc.wxwork_userid = dept_user['userid']
                doc.wxwork_name = user_info['name']
                if 'email' in user_info:
                    doc.wxwork_email = user_info['email']
                if 'mobile' in user_info:
                    doc.wxwork_phone =  user_info['mobile']
                doc.insert()
            else:
                doc = frappe.get_doc('wxwork_user_mapping',dept_user['userid']) 
                doc.wxwork_name = user_info['name']
                if 'email' in user_info:
                    doc.wxwork_email = user_info['email']
                if 'mobile' in user_info:
                    doc.wxwork_phone =  user_info['mobile']
                doc.save()


@frappe.whitelist(allow_guest=True)    
def wxwork_login(code):
    print(code)
    wxwork_token = get_token()   
    kw2 = {'access_token':wxwork_token,'code':code}
    response2 = requests.get("https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?", params = kw2)
    login_user = response2.json()
    print(login_user)
    if login_user['errcode'] != 0:
        return login_user['errmsg']
    frappe.local.cookie_manager.set_cookie("wxwork_user", login_user['userid'])
    if not frappe.db.exists('wxwork_user_mapping', login_user['userid']):        
        frappe.local.response["type"] = "redirect"
        frappe.local.response["location"] = '/login?redirect-to=%2Fapp%2Fwxwork_bind'
        return 
    else:
        user_mapping = frappe.get_doc('wxwork_user_mapping',login_user['userid']) 
        frappe.local.login_manager.user = user_mapping.link_user
        frappe.local.login_manager.post_login()
        frappe.local.response["type"] = "redirect"
        frappe.local.response["location"] = '/app'

@frappe.whitelist(allow_guest=True) 
def bind_user(wxwork_user,en_user):
    # create a new document
    doc = frappe.new_doc('wxwork_user_mapping')
    doc.wxwork_userid = wxwork_user
    doc.link_user = frappe.session.user
    doc.insert()